package com.example.androidframework.ui.exchange

import android.util.Log
import com.example.androidframework.ui.exchange.holder.ExchangeGoodsViewHolder
import com.example.androidframework.ui.goods.GoodsDetailActivity
import com.example.androidframework.ui.login.LoginActivity
import com.martin.lib_base.LibBase
import com.martin.lib_base.base.BasePageViewModel
import com.martin.lib_base.bean.app.exchange.GoodsCategoryBean
import com.martin.lib_base.bean.app.mall.HomeMallBean
import com.martin.lib_base.ktx.loge
import com.martin.lib_base.ktx_live.buildRequest
import com.martin.lib_base.ktx_live.launchCollect
import com.martin.lib_base.ktx_live.launchLoadingCollect
import com.martin.lib_base.net.NetApply
import kotlinx.coroutines.flow.MutableStateFlow

class ExchangeViewModel : BasePageViewModel() {

    val viewHolder = listOf(ExchangeGoodsViewHolder::class.java)
    var categoryList = MutableStateFlow<ArrayList<GoodsCategoryBean>>(arrayListOf())
    var categoryId = MutableStateFlow("")
    var keyword = MutableStateFlow("")
    var mallData = MutableStateFlow<HomeMallBean>(HomeMallBean())

    /// 获取分类数据
    fun getCategoryData() {
        launchLoadingCollect({
            NetApply.api.getCategoryList(
                buildRequest(
                    "Shop.Category"
                )
            )
        }) {
            onSuccess = {
                it.info?.let { value ->
                    categoryList.value = value
                    categoryId.value = categoryList.value.firstOrNull()?.gc_id ?: ""
                }
            }
        }
    }

    /**
     * 获取商品数据
     */
    override fun getData() {
        launchCollect({
            NetApply.api.getCategoryGoodsList(
                buildRequest(
                    "Home.GetModularList", mapOf(
                        "p" to pageModel.page,
                        "search_name" to keyword.value,
                        "category_id" to categoryId.value,
                        "type" to 3
                    )
                )
            )
        }) {
            onSuccess = {
                it.info?.let {
                    loge("onSuccess goods_list size ====== ${it.goods_list?.size}")
                    mallData.value = it
                }
            }
        }
    }

    fun goPage(id: String) {
        if (LibBase.isLogin.value == true) {
            GoodsDetailActivity.start(context, id)
        } else {
            LoginActivity.start(context)
        }
    }
}